package com.reader.cms.controller.sys;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.reader.cms.controller.BaseController;
import com.reader.cms.entity.sys.SysCommDetail;
import com.reader.cms.entity.sys.SysCommMaster;
import com.reader.cms.mapper.sys.SysCommMasterMapper;
import com.reader.cms.service.sys.ISysCommDetailService;
import com.reader.cms.service.sys.ISysCommMasterService;
import com.reader.core.entity.ResultMessageInfo;
import com.reader.core.exception.CustomException;
import com.reader.core.utils.ValidatorUtil;
import com.reader.core.validator.group.AddGroup;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description   功能描述
 * @author        jiahaikun
 * @date          2018-08-06
 */
@RestController
@RequestMapping("/api/SysCommMaster")
public class SysCommMasterController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(SysCommMasterController.class);

    @Autowired
    public ISysCommMasterService iSysCommMasterService;

    @Autowired
    SysCommMasterMapper sysCommMasterMapper;

    @Autowired
    ISysCommDetailService iSysCommDetailService;

    /**
     * @function 分页查询数据
     *
     * @param currentPage   当前页
     * @param size   每页记录数
     * @param  name  名称
     * @return
     */
    @GetMapping("list")
    public ResultMessageInfo selectListPage(@RequestParam(value = "currentPage") int currentPage ,
                                                    @RequestParam(value = "size") int size,
                                                    @RequestParam(value = "masterKey") String masterKey,
                                                    @RequestParam(value = "name") String name,
                                                    @RequestParam(value = "codeKey") String codeKey,
                                                    @RequestParam(value = "codeValue") String codeValue) {
        ResultMessageInfo resultMessage=null;
        Page<Map<String, Object>> list=iSysCommMasterService.selectListPage(currentPage,size,masterKey,name,codeKey,codeValue);
        return ResultMessageInfo.ofSuccess("查询成功！", list);
    }

    /**
     * @function 添加新记录
     * @param sysCommMaster 实体对象
     * @return
     */
    @PostMapping("insert")
    public ResultMessageInfo insert(@RequestBody SysCommMaster sysCommMaster) {
        ValidatorUtil.validateEntity(sysCommMaster, AddGroup.class);//非空验证
        sysCommMaster.setInsertDt(new Date());
        EntityWrapper<SysCommMaster> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag",0).eq("master_key",sysCommMaster.getMasterKey());
        Integer masterCount = sysCommMasterMapper.selectCount(wrapper);
        if(masterCount != 0){
            return ResultMessageInfo.ofMessage("公共代码编码已存在！！！");
        }
        Integer userId = this.getUserId();
        sysCommMaster.setEnable(1);
        sysCommMaster.setDelFlag(0);
        sysCommMaster.setInsertUserId(userId);
        sysCommMaster.setUpdtUserId(userId);
        boolean resultValue =  iSysCommMasterService.insertOrUpdate(sysCommMaster);
        if(!resultValue){
            ResultMessageInfo.ofMessage("添加失败！");
        }
        return  ResultMessageInfo.ofSuccess("添加成功！");
    }

    /**
     * @function 修改
     * @param sysCommMaster 实体对象
     * @return
     */
    @PostMapping("update")
    @Transactional
    @ApiOperation(value="跟据ID列新记录", notes="id为必须项")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "要更新对象ID", required = true, dataType = "int",paramType = "path")})
    public ResultMessageInfo update(@RequestBody  SysCommMaster sysCommMaster) {
        sysCommMaster.setUpdtDt(new Date());
        sysCommMaster.setUpdtUserId(this.getUserId());
        ValidatorUtil.validateEntity(sysCommMaster, AddGroup.class);//非空验证
        EntityWrapper<SysCommMaster> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag",0).eq("master_key",
                sysCommMaster.getMasterKey()).ne("id",sysCommMaster.getId());
        Integer masterCount = sysCommMasterMapper.selectCount(wrapper);
        if(masterCount != 0){
            return ResultMessageInfo.ofMessage("公共代码编码已存在！！！");
        }
        sysCommMaster.setDelFlag(0);
        boolean resultValue =  iSysCommMasterService.updateById(sysCommMaster);
        if (!resultValue) {
            return ResultMessageInfo.ofMessage("修改失败！");
        }
        return ResultMessageInfo.ofSuccess("修改成功！");
    }

    /**
     * @function 删除
     * @param sysCommMaster 实体对象
     * @return
     */
    @PostMapping("delete")
    @Transactional
    @ApiOperation(value="跟据ID列新记录", notes="id为必须项")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "要更新对象ID", required = true, dataType = "int",paramType = "path")})
    public ResultMessageInfo delete(@RequestBody  SysCommMaster sysCommMaster) {
        sysCommMaster.setDelFlag(1);
        sysCommMaster.setUpdtDt(new Date());
        sysCommMaster.setUpdtUserId(this.getUserId());
        ResultMessageInfo resultMessage=null;
        boolean resultValue =  iSysCommMasterService.updateById(sysCommMaster);
        if (!resultValue) {
//            List<SysCommDetail> details = iSysCommDetailService.getDetail(sysCommMaster.getMasterKey());
//            if(details.size() != 0){
//                details.forEach((detail) ->{detail.setDelFlag(1);});
//                iSysCommDetailService.updateBatchById(details);
//            }
//        } else {
            return ResultMessageInfo.ofMessage("删除失败！");

        }
        return ResultMessageInfo.ofSuccess("删除成功！");
    }

    /**
     * @function 批量删除对象
     * @param data 键为ids值为整型数组的json格式
     * @return
     */
    @PostMapping("deleteIds")
    @Transactional
    @ApiOperation(value="根据ID删除记录", notes="键为ids值为整型数组的json格式")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "id列表", required = true, dataType = "int",paramType = "path")})
    public ResultMessageInfo deleteBatchIds(@RequestBody String data){
        ResultMessageInfo resultMessage=null;
        List<Long> ids = JSON.parseArray( JSON.parseObject(data).getString("ids"),Long.class);
        boolean resultValue =  iSysCommMasterService.deleteBatchIds(ids);
        if(resultValue){
            resultMessage = ResultMessageInfo.ofSuccess("删除成功!",resultValue);
        }
        else{
            return ResultMessageInfo.ofMessage("删除失败!");


        }
        return resultMessage;

    }
}